package com.learn.security.modules.wx.mp.controller;

import com.learn.security.modules.vo.R;
import com.learn.security.modules.wx.mp.config.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lee
 */
@Slf4j
@RequestMapping("/wx/qrcode")
@RestController
public class WxQrCodeController {

    @Autowired
    private WxMpService wxService;
    @Autowired
    private WxMpProperties properties;

    /**
     * 获取微信二维码url
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/pictureUrl")
    public R qrCodeUrl(@RequestParam String sceneStr) throws WxErrorException {
        List<WxMpProperties.MpConfig> configs = properties.getConfigs();
        String appId = configs.get(0).getAppId();
        if (!this.wxService.switchover(appId)) {
            log.info(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
            throw new BadCredentialsException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        // 二维码30分钟内有效
        WxMpQrCodeTicket ticket = wxService.getQrcodeService().qrCodeCreateTmpTicket(sceneStr, 1800);
        return R.ok().put("qrCodeUrl", wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket()));
    }

}
